package com.kylin.module.shop.business;

import java.io.IOException;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import org.apache.log4j.Logger;
import org.apache.struts.upload.FormFile;
import org.hibernate.criterion.Projection;
import org.hibernate.criterion.Projections;

import com.kylin.common.Constants;
import com.kylin.common.dict.orm.Dict;
import com.kylin.common.exception.BusinessException;
import com.kylin.common.paginate.DisplayPage;
import com.kylin.common.paginate.PageManager;
import com.kylin.common.util.Config;
import com.kylin.common.util.FileOperater;
import com.kylin.hibernate.BaseHibernateDAO;
import com.kylin.hibernate.CriteriaInfo;
import com.kylin.hibernate.PropertyCondition;
import com.kylin.module.shop.forms.AdvisoryForm;
import com.kylin.module.shop.forms.CompanyForm;
import com.kylin.module.shop.forms.InquiryForm;
import com.kylin.module.shop.forms.OrderForm;
import com.kylin.module.shop.forms.ProductForm;
import com.kylin.module.shop.forms.SearchDiskForm;
import com.kylin.module.shop.orm.Advisory;
import com.kylin.module.shop.orm.Company;
import com.kylin.module.shop.orm.CompanyCat;
import com.kylin.module.shop.orm.CompanyInd;
import com.kylin.module.shop.orm.Content;
import com.kylin.module.shop.orm.Inquiry;
import com.kylin.module.shop.orm.Order;
import com.kylin.module.shop.orm.Product;
import com.kylin.module.shop.orm.Searchdisk;
import com.kylin.module.user.orm.User;

public class CompanyBlogic {
	protected static Logger log = Logger.getLogger(CompanyBlogic.class);
	
	/** 展示区最大数量 */
	private int showLimit = 20;

	/**
	 * 修改公司信息
	 * @param form
	 * @throws BusinessException 
	 */
	public Company updateCompany(CompanyForm form) throws BusinessException{
 		Company com = (Company) BaseHibernateDAO.findById(Company.class, form.getId());
 		if( (com.getName()==null || com.getName().equals("") )
 				&& form.getName() != null 
 				&& !"".equals(form.getName())){
	 		Company searchExample = new Company();
	 		searchExample.setLanguage(form.getLanguage());
	 		searchExample.setName(form.getName());
	 		List sames = BaseHibernateDAO.findByExample(searchExample);
	 		if(sames != null && sames.size() > 0)
	 			throw new BusinessException("已经有同名的公司("+form.getName()+")存在，请更改公司名称");
			com.setName(form.getName());
 		}
		com.setContact(form.getContact());
		com.setAddress(form.getAddress());
		com.setCompanyIntro(form.getCompanyIntro());
		com.setEmail(form.getEmail());
		com.setFax(form.getFax());
		com.setFaxArea(form.getFaxArea());
		com.setFaxCountry(form.getFaxCountry());
		com.setPhone(form.getPhone());
		com.setPhoneArea(form.getPhoneArea());
		com.setPhoneCountry(form.getPhoneCountry());
		com.setPostcode(form.getPostcode());
		com.setCompanyIntro(form.getCompanyIntro());
		if(form.getMainbusiness() != null)
			for(int k=0;k<form.getMainbusiness().length;k++){
				//商家的主营行业 
				Dict industry = (Dict) BaseHibernateDAO
								.findById(Dict.class, form.getMainbusiness()[k]);
				CompanyInd ci = new CompanyInd(industry,com,new Date());
				com.getMainbusiness().add(ci);
			}
			if(form.getMaincatproduct() != null)
			for(int k=0;k<form.getMaincatproduct().length;k++){
				//商家的 主营商品类别
				Dict catproduct = (Dict) BaseHibernateDAO
								.findById(Dict.class, form.getMaincatproduct()[k]);
				CompanyCat cp = new CompanyCat(catproduct, com,new Date() );
				com.getMaincatproduct().add(cp);
			}
		if(form.getLogo()!= null 
				&& form.getLogo().getFileName()!= null 
				&& form.getLogo().getFileSize() >0){
			String logoImg = uploadImage("logo",form.getLogo(),com.getLogo());
			if(logoImg != null)
				com.setLogo( logoImg );
		}
		if(form.getAdImg()!= null 
				&& form.getAdImg().getFileName()!= null 
				&& form.getAdImg().getFileSize() >0){
			String ADImg = uploadImage("AD",form.getAdImg(),com.getAdImg());
			if(ADImg != null)
				com.setAdImg( ADImg);
		}
		log.debug("\nSave com="+com.getName() +"("+com.getLanguage()+")");
		BaseHibernateDAO.update(com);
		return com;

	}
	
	public Long[] getCompanyIdByCatP(Long catId) throws BusinessException{
		List rs =BaseHibernateDAO.findByProperty(CompanyCat.class, "catproduct.id", catId);
	   List ids = new LinkedList();
		for(int i=0;i<rs.size();i++){
	    	CompanyCat cc = (CompanyCat)rs.get(i);
	    	ids.add(cc.getCompany().getId());
	    }
		return (Long[])ids.toArray(new Long[0]);
	}
	
	/**
	 * 上传图片。如果存在oldFile值，上传新图片后将删除oldFile
	 * @param String flag 图片类别标志
     *        logo: 公司logo
     *        AD  : 公司店内广告
     *        product: 产品图片
	 * @param formFile 上传的文件
	 * @param oldFile  已存在的旧文件（update图片时需要）
	 * @return
	 * @throws BusinessException
	 */
	private String uploadImage(String flag,FormFile formFile,String oldFile) throws BusinessException{
    log.debug("uploadImage(flag="+flag+" ,formFile="+formFile+" ,oldFile="+oldFile+")" );
		String imgUrl = null;
		if (formFile != null 
				&& formFile.getFileSize() > 0
				&& formFile.getFileName() != null
				&& !formFile.getFileName() .equals("")) {
log.debug(" FileSize()="+formFile.getFileSize() + ", FileName()="+formFile.getFileName());			
			if(formFile.getFileSize() > Config.uploadMaxSize*1024)
				throw new BusinessException("上传文件尺寸最大不能超过 "+Config.uploadMaxSize+" KB");
			try{
				if(oldFile == null || oldFile.equals("")){
					if("logo".equals(flag))
						imgUrl = FileOperater.saveUploadFile(Constants.IMG_COMPANYLOGO,formFile.getInputStream(), formFile.getFileName());
					if("AD".equals(flag))
						imgUrl = FileOperater.saveUploadFile(Constants.IMG_COMPANYAD,formFile.getInputStream(), formFile.getFileName());
					if("product".equals(flag))
						imgUrl = FileOperater.saveUploadFile(Constants.IMG_PRODUCT,formFile.getInputStream(), formFile.getFileName());
				}else{
					if("logo".equals(flag))
						imgUrl = FileOperater.updateUploadFile(Constants.IMG_COMPANYLOGO,formFile.getInputStream(), formFile.getFileName(),oldFile);
					if("AD".equals(flag))
						imgUrl = FileOperater.updateUploadFile(Constants.IMG_COMPANYAD,formFile.getInputStream(), formFile.getFileName(),oldFile);
					if("product".equals(flag))
						imgUrl = FileOperater.updateUploadFile(Constants.IMG_PRODUCT,formFile.getInputStream(), formFile.getFileName(),oldFile);
				}
			}catch(IOException e){
				throw new BusinessException("不能读取上传的文件："+e,e);
			}
		}else{
			imgUrl = oldFile;
		}
		return imgUrl;
	}
	
	/**
	 * 根据username获取登录用户的User对象，包含所属公司
	 * @param userName
	 * @return
	 * @throws BusinessException
	 */
	public User getLoginUser(String userName,String language) throws BusinessException {
		User guest = new User();
		guest.setUsername(userName);
		List list = BaseHibernateDAO.findByExample(guest);
		if (list == null || list.size() == 0) {
			throw new BusinessException("用户名或密码错误");
		}
		
		User user = (User) list.get(0);
		List coms = BaseHibernateDAO.findByProperty(Company.class, "user", user);
		boolean disab =true;
		for(int i=0;i<coms.size();i++){
			Company com = (Company)coms.get(i);
			if(com.getLanguage()!= null && com.getLanguage().equals(language))
				disab = false;
		}
		if(disab)
			throw new BusinessException ("loginErr.notbuyThisLanguage","很报歉，您暂未购买此版本，请在您购买的版本上登录。如需购买此版本，请与我们联系！");
		user.setSubs(coms);
		return user;
	}

	public void addProduct(ProductForm form) throws BusinessException {
		Company com = (Company) BaseHibernateDAO.findById(Company.class, form.getCompany());
//		Product same = new Product();
//		same.setCompany(com);
//		same.setName(form.getName());
//		List sames = BaseHibernateDAO.findByExample(same);  //TODO 临时注释，要修改，目前不能正确检查
//		if (sames != null && sames.size() > 0)
//			throw new BusinessException("已经存在同名商品");
		Product p = new Product();
		p.setName(form.getName());
		p.setActive(Product.ACTIVE_INDB);
		p.setCompany(com);
		p.setOrdering(new Integer("1000") );
		p.setCreatedon(new Date());
		p.setLastupdatedon(p.getCreatedon());
		p.setPrice(form.getPrice());
		
		// 下拉菜单需要检查数据是否有效，0L表示客户端未选择
		if(! new Long(0L).equals(form.getCatproduct()))
			p.setCatproduct(new Dict(form.getCatproduct()));
		if(! new Long(0L).equals(form.getUnit()))
			p.setUnit( new Dict(form.getUnit()) );
		if(! new Long(0L).equals(form.getCurrency()))
			p.setCurrency(new Dict(form.getCurrency()));
		
		p.setQuantity(form.getQuantity());
		p.setImgurl( uploadImage("product",form.getImgFile(),null) );
		p.setIntroduce(form.getIntroduce());
		p.setLanguage(com.getLanguage());
		BaseHibernateDAO.save(p);
	}

	/**
	 * 根据id 查询产品对象
	 * @param sid 字符型产品id
	 * @return
	 * @throws BusinessException
	 */
	public Product getProduct(String sid) throws BusinessException{
		Long lid = new Long(sid);
		return (Product)BaseHibernateDAO.findById(Product.class, lid);
	}

	/**
	 * 根据id 查询贸易信息对象
	 * @param sid 字符型贸易信息id
	 * @return
	 * @throws BusinessException
	 */
	public Content getContent(String sid) throws BusinessException{
		Long lid = new Long(sid);
		return (Content)BaseHibernateDAO.findById(Content.class, lid);
	}

	/**
	 * 根据id 查询订单
	 * @param sid 字符型id
	 * @return
	 * @throws BusinessException
	 */
	public Order getOrder(String sid) throws BusinessException{
		Long lid = new Long(sid);
		return (Order)BaseHibernateDAO.findById(Order.class, lid);
	}

	public Product updateProduct(ProductForm form) throws BusinessException {
		Company com = (Company) BaseHibernateDAO.findById(Company.class, form.getCompany());
		Product same = new Product();
		same.setCompany(com);
		same.setName(form.getName());
		List sames = BaseHibernateDAO.findByExample(same);
		if (sames != null && sames.size() > 0){
			for(int i=0;i<sames.size();i++){
				if( !((Product)sames.get(i)).getId().equals(form.getId()) )
			    throw new BusinessException("已经存在同名商品");
			}
		}
		Product p = (Product) BaseHibernateDAO.findById(Product.class, form.getId());
		p.setName(form.getName());
		p.setCompany(com);
		// p.setCreatedby(createdby)
		p.setLastupdatedon(new Date());
		p.setPrice(form.getPrice());
		p.setQuantity(form.getQuantity());
		
		// 下拉菜单需要检查数据是否有效，0L表示客户端未选择
		if(! new Long(0L).equals(form.getCatproduct()))
			p.setCatproduct(new Dict(form.getCatproduct()));
		if(! new Long(0L).equals(form.getUnit()))
			p.setUnit( new Dict(form.getUnit()) );
		if(! new Long(0L).equals(form.getCurrency()))
			p.setCurrency(new Dict(form.getCurrency()));
		if(form.getImgFile() != null 
				&& form.getImgFile().getFileName() != null
				&& !form.getImgFile().getFileName() .equals(""))
			p.setImgurl( uploadImage("product",form.getImgFile(),p.getImgurl()) );
		p.setIntroduce(form.getIntroduce());
		BaseHibernateDAO.saveOrUpdate(p);
		return p;
	}

	/**
	 * 删除产品的业务方法
	 * @param id
	 * @throws BusinessException
	 */
	public void deleteProduct(Long id) throws BusinessException {
		Product p = (Product) BaseHibernateDAO.findById(Product.class, id);
		BaseHibernateDAO.delete(p);
		try {
			FileOperater.deleteFile(Constants.IMG_PRODUCT,p.getImgurl());
		} catch (IOException e) {
			log.error("删除产品["+p.getName()+"]图片失败: "+e);
			throw new BusinessException("删除产品["+p.getName()+"]图片失败: "+e);
		}
	}

	/**
	 * 将产品加入到展示区
	 * @param id
	 * @throws BusinessException
	 */
	public int toShowProducts(String[] ids,Long companyId) throws BusinessException {
		Projection p = Projections.rowCount();
		Company currCom = (Company)BaseHibernateDAO.findById(Company.class, companyId);
		PropertyCondition[] pConditions = new PropertyCondition[]{
				new PropertyCondition("company", currCom,PropertyCondition.OPERATOR_EQ ),
				new PropertyCondition("active", Product.ACTIVE_SHOW,PropertyCondition.OPERATOR_EQ )
		};
		List rs = BaseHibernateDAO.selectByConditionsForProjection(Product.class, pConditions, p);
		int num = 0;
		if(rs != null)
			num = new Integer(rs.get(0).toString()).intValue() ;
		if(num < this.showLimit){
			String hsql = "update Product set active="+Product.ACTIVE_SHOW;
			for(int i=0;i<ids.length && num+i <=this.showLimit;i++){
				if(i==0)
					hsql += " where ";
				else
					hsql += " or " ;
				hsql += " id=" + ids[i];
			}
			return BaseHibernateDAO.execHql(hsql) ;
		}else
			throw new BusinessException("展示区位置已满，最多只能展示 " + this.showLimit);
	}

	/**
	 * 将产品入库
	 * @param id
	 * @throws BusinessException
	 */
	public int toProductsDB(String[] ids) throws BusinessException {
		String hsql = "update Product set active="+Product.ACTIVE_INDB;
		for(int i=0;i<ids.length ;i++){
			if(i==0)
				hsql += " where ";
			else
				hsql += " or " ;
			hsql += " id=" + ids[i];
		}
		return BaseHibernateDAO.execHql(hsql) ;
	}

	/**
	 * 将产品入库
	 * @param id
	 * @throws BusinessException
	 */
	public void changePassword(String userId,String oldPass,String newPass) throws BusinessException {
		User user = (User) BaseHibernateDAO.findById(User.class, new Long(userId) );
		if(user == null)
			throw new BusinessException("未找到用户信息");
		if(! oldPass.equals(user.getPassword()))
			throw new BusinessException("输入的原密码不正确");
		user.setPassword(newPass);
		BaseHibernateDAO.save(user) ;
	}

	public static void main(String[]s) throws Exception{
		CompanyBlogic blogic = new CompanyBlogic();
		blogic.toShowProducts(new String[]{"3","4"},new Long("2"));
	}
	public DisplayPage getProductList(int pageSize, int pageNum, CriteriaInfo cinfo) throws BusinessException {
		log.info("search page " + pageNum);
		DisplayPage page = PageManager.getDisplayPage(pageSize, pageNum, cinfo);
		return page;
	}

	/**
	 * 保存订单
	 * @param form
	 * @throws BusinessException
	 */
	public void saveOrder(OrderForm form) throws BusinessException{
		Order obj = new Order();
		Product p = (Product) BaseHibernateDAO.findById(Product.class, form.getProductId());
		obj.setProduct(p);
		obj.setQuantity      (form.getQuantity  () );   
		obj.setPrice         (form.getPrice     () );   
		obj.setTotal         (form.getTotal     () );   
		obj.setOrderStatus(new Short("0"));   
		obj.setAddress       (form.getAddress   () );    
		obj.setEmail         (form.getEmail     () );     
		obj.setPostcode      (form.getPostcode  () );     
		obj.setPhoneCountry(form.getPhone_country () );     
		obj.setPhoneArea(form.getPhone_area() );     
		obj.setPhone         (form.getPhone     () );     
		obj.setFaxCountry(form.getFax_country   () );     
		obj.setFaxArea      (form.getFax_area   () );     
		obj.setFax           (form.getFax       () );     
		obj.setContact       (form.getContact   () );     
		obj.setMemo          (form.getMemo      () );  
		obj.setCreatedon(new Date());
		if(obj.getQuantity().intValue() < 1)
			throw new BusinessException("订购数量不能小于1");
		BaseHibernateDAO.save(obj) ;
	}
	
	/**
	 * 保存在线咨询信息
	 * @param form
	 * @throws BusinessException
	 */
	public void saveAdvisory(AdvisoryForm form) throws BusinessException{
		log.debug("保存在线咨询信息  ("+form.getCompanyId()+")  "+form.getTitle());
		Advisory obj = new Advisory();		
		obj.setTitle(form.getTitle());
		obj.setCompany(new Company(form.getCompanyId() ));
		obj.setCountry(form.getCountry());
		obj.setContent(form.getContent());
		obj.setAddress       (form.getAddress   () );    
		obj.setEmail         (form.getEmail     () );     
		obj.setPostcode      (form.getPostcode  () );     
		obj.setPhoneCountry(form.getPhoneCountry() );     
		obj.setPhoneArea(form.getPhoneArea() );     
		obj.setPhone         (form.getPhone     () );     
		obj.setFaxCountry(form.getFaxCountry() );     
		obj.setFaxArea      (form.getFaxArea() );     
		obj.setFax           (form.getFax       () );     
		obj.setContact       (form.getContact   () ); 
		obj.setCreatedon(new Date());
		obj.setLastupdatedon(new Date());
		BaseHibernateDAO.save(obj) ;
	}
	
	/**
	 * 保存用户对产品询问信息
	 * @param form
	 * @throws BusinessException
	 */
	public void saveInquiry(SearchDiskForm form, Product p, User user) 
	{
		try {		
			log.debug("保存产品询问信息:"+form.getTitle());
			Searchdisk obj = new Searchdisk();
			obj.setCompanyname(form.getCompanyname());
			obj.setContents(form.getContents());
			obj.setCountry(form.getCountry());
			obj.setCreatetime(new Date());
			obj.setEmail(form.getEmail());
			obj.setGender(form.getGender());
			obj.setLanguage(form.getLanguage());
			//Dict dict_m = new Dict(form.getMainbussiness());
			obj.setMainbussiness(form.getMainbussiness());
		
			obj.setPhone(form.getPhone());
			obj.setAreaphone(form.getAreaphone());
			obj.setCountryphone(form.getCountryphone());
			//Dict dict_p = new Dict(form.getPositions());
		    obj.setFkPositionId(form.getFkPositionId());
			obj.setFkProductId(form.getFkProductId());
			obj.setFkMembersId(p.getCompany().getId());
			obj.setValidationCode(form.getValidationCode());
			obj.setWebsite(form.getWebsite());
			obj.setUserIp(form.getUserIp());
			obj.setTitle(form.getTitle());
			obj.setLinkman(form.getLinkman());
			
			System.out.println("联系人"+form.getLinkman());
			System.out.println("网页"+form.getWebsite());
			//obj.setCurrUser(user);
			obj.setProduct(p);
			BaseHibernateDAO.save(obj);
			
		} catch (BusinessException e) {
				e.printStackTrace();
			}
		}
	
}
